package com.lc1993929.mr.friends;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;

import java.io.IOException;

/**
 * Created by LiuChang on 2017/11/24/024.
 */
public class CommonFriendsStepTwo {

    static class CommonFriendsStepTwoMapper extends Mapper<LongWritable, Text, Text, Text> {
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String[] split = value.toString().split("\t");
            String userPair = split[0];
            String friend = split[1];
            context.write(new Text(userPair), new Text(friend));
        }
    }

    static class CommonFriendsStepTwoReducer extends Reducer<Text, Text, Text, Text> {
        @Override
        protected void reduce(Text userPair, Iterable<Text> friends, Context context) throws IOException, InterruptedException {
            StringBuilder sb = new StringBuilder();
            for (Text f : friends) {
                sb.append(f).append(",");
            }
            context.write(userPair, new Text(sb.toString()));
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        Configuration conf = new Configuration();
        //conf.set("mapreduce.framework.name", "local");
        Job job = Job.getInstance(conf);
        //要执行的jar文件
        job.setJarByClass(CommonFriendsStepTwo.class);
        //指定mapper类和reducer类
        job.setMapperClass(CommonFriendsStepTwoMapper.class);
        job.setReducerClass(CommonFriendsStepTwoReducer.class);
        //指定mapper和reducer的输出的key和value的数据类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        //指定要解析的文件类型
        job.setInputFormatClass(TextInputFormat.class);
        //指定要解析的文件路径
        FileInputFormat.setInputPaths(job, new Path("/project/hadoop/mapreduce/src/main/java/com/lc1993929/mr/friends/output"));
        //指定要输出的文件类型
        job.setOutputFormatClass(TextOutputFormat.class);
        //指定输出的文件路径
        FileOutputFormat.setOutputPath(job, new Path("/project/hadoop/mapreduce/src/main/java/com/lc1993929/mr/friends/output2"));

        job.setNumReduceTasks(1);
        // 向yarn提交job
        boolean res = job.waitForCompletion(true);

        System.exit(res ? 0 : 1);
    }
}
